<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\AreaModel;
use App\Services\Cache;
use Carbon\Carbon;

class AreaDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
            $query = AreaModel::query();

            $query->when(checkIsHasField($params,'area_id'),function ($query)use ($params){
                $query->where('area_id',$params['area_id']);
            });

            $query->when(checkIsHasField($params,'level'),function ($query)use ($params){
                $query->where('level',$params['level']);
            });


            $query->when(checkIsHasField($params,'parentid'),function ($query)use ($params){
                $query->where('parentid',$params['parentid']);
            });




            return $query;
    }

    public static function areas($params = [])
    {
        return self::builder_query($params)->orderByDesc('area_id')->paginate();
    }

    public static function areasNoData($params = [])
    {
        return self::builder_query($params)->get()->toArray();
    }


    /**
     * @throws SysExceptions
     */
    public static function add($params = [])
    {
        checkForData(['name','parentid'],['请输入地区名称','请选地区上级'],$params);
        $params['level'] = AreaDao::builder_query(['area_id'=>$params['parentid']])->value('level')+1;
        if (self::builder_query()->create($params) === false){
            self::error('添加失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function edit($params = [])
    {
        checkForData(['name','parentid','area_id'],['请输入地区名称','请选地区上级','请选择地区'],$params);
        if(self::builder_query(['area_id'=>self::deleteParamId($params,'area_id')])->update(self::filterFields($params,new AreaModel())) === false){
            self::error('修改失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function delete($id)
    {
        if(self::builder_query(['area_id'=>$id])->delete() === false){
            self::error('删除成功');
        }
    }

    public static function areasChild(array $array)
    {
        if(Cache::hasCache('APP_AREA123')){
            return Cache::getCacheValue('APP_AREA123');
        }
        $lists =  self::builder_query([
            'level'=>1
        ])->with('childs.childs.childs')->select(['area_id','name'])->get()->toArray();
        Cache::setCache('APP_AREA123',$lists,Carbon::now()->addMinutes(5));
        return $lists;
    }
}
